﻿using Common.Logging;
using NHibernate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Xmart.Action
{
    public class ModelAction : AbstractAction
    {
        public ModelAction(ISessionFactory sessionFactory)
        {
            SessionFactory = sessionFactory;
        }

        public ISessionFactory SessionFactory
        {
            get
            {
                return Template.SessionFactory;
            }
            set
            {
                Template = new Spring.Data.NHibernate.Generic.HibernateTemplate(value);
            }
        }

        protected Spring.Data.NHibernate.Generic.HibernateTemplate Template { get; set; }

        ILog log = LogManager.GetCurrentClassLogger();

        #region 方法

        public ActionResult ExecuteSave(object model)
        {
            var ar = new ActionResult();
            Template.SaveOrUpdate(model);
            return ar;
        }

        public ActionResult ExecuteDelete(object model)
        {
            var ar = new ActionResult();
            Template.Delete(model);
            return ar;
        }

        public ActionResult ExecuteFind<T>(Func<ISession, IList<T>> func)
        {
            var ar = new ActionResult();
            ar.Data = Template.ExecuteFind<T>(delegate(NHibernate.ISession s)
            {
                return func(s);
            });
            return ar;
        }

        public ActionResult Load<T>()
        {
            var ar = new ActionResult();
            ar.Data = Template.LoadAll<T>();
            return ar;
        }

        public ActionResult Load<T>(object id)
        {
            var ar = new ActionResult();
            ar.Data = Template.Get<T>(id);
            return ar;
        }

        public ActionResult Find<T>(string query)
        {
            var ar = new ActionResult();
            ar.Data = Template.Find<T>(query);
            return ar;
        }

        public ActionResult Find<T>(string query, object[] values)
        {
            var ar = new ActionResult();
            ar.Data = Template.Find<T>(query, values);
            return ar;
        }

        #endregion


    }
}
